package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        List<Double> turnoverList = new ArrayList<>();

        dateList.forEach(date -> {
            Map<Object, Object> turnover = new HashMap<>();
            turnover.put("status", Orders.COMPLETED);
            turnover.put("beginTime", LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime())); // 2025-5-15 00:00
            turnover.put("endTime", LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime())); // 2025-5-15 23:59:59.9999
            Double turnoverCount = ordersMapper.sumTurnoverByDate(turnover);
            // 用来处理没有新用户的情况
            turnoverCount = turnoverCount == null ? 0.0 : turnoverCount;
            turnoverList.add(turnoverCount);
        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        List<Integer> newUserList = new ArrayList<>();

        List<Integer> totalUserList = new ArrayList<>();

        dateList.forEach(date -> {
            Map<Object, Object> map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime()));
            map.put("endTime", LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime()));
            Integer newUserCount = userMapper.countByCreateTime(map);
            map.put("beginTime", null);
            map.put("endTime", LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime()));
            Integer totalUserCount = userMapper.countByCreateTime(map);
            newUserList.add(newUserCount);
            totalUserList.add(totalUserCount);
        });
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        // 2. 获取每日总订单列表数orderCountList
        List<Integer> orderCountList = new ArrayList<>();

        //3.获取每日有效订单列表数validOrderCountList
        List<Integer> validOrderCountList = new ArrayList<>();

        // 4.获取订单总数totalOrderCount
        Integer totalOrderCount = 0;

        // 5.获取有效订单数validOrderCount
        Integer validOrderCount = 0;

        // 6. 计算完成率orderCompletionRate
        Double orderCompletionRate = 0.0;

        for (LocalDate date : dateList) {
            Map<Object, Object> map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime()));
            map.put("endTime", LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime()));
            Integer totalOrders = ordersMapper.selectCount(map);
            orderCountList.add(totalOrders);
            map.put("status", Orders.COMPLETED);
            Integer vaildOrders = ordersMapper.selectCount(map);
            validOrderCountList.add(vaildOrders);
            totalOrderCount += totalOrders;
            validOrderCount += vaildOrders;
        }
        if (totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();  // 这里用Object类型，因为可能是Double类型

        Map<String, Object> map = new HashMap<>();
        map.put("status", Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalDateTime.MIN.toLocalTime()));
        map.put("endTime", LocalDateTime.of(end, LocalDateTime.MAX.toLocalTime()));
        List<GoodsSalesDTO> top10 = ordersMapper.sumTop10(map);

        for (GoodsSalesDTO item : top10) {
            nameList.add(item.getName());
            numberList.add(item.getNumber());
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 获取日期列表
     *
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        // 循环插入日期数据
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }
}
